package com.itheima.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Employee;
import com.itheima.common.ParamPage;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @PostMapping("/login")
    private R login(@RequestBody Employee employee, HttpSession session){
        Employee employee1 = employeeService.findOne(employee);
        if (employee1!=null){
            session.setAttribute("employee",employee1);
            return R.success(employee1);
        }
        return R.error("登录失败！");
    }
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.success("退出登录成功！");
    }
    @PostMapping
    public R add(@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        Employee employee1 = (Employee) session.getAttribute("employee");
//        employee.setCreateUser(employee1.getId());
//        employee.setUpdateUser(employee1.getId());
        int i = 0;
        try {
            i = employeeService.add(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i>0){
         return R.success("添加员工成功！");
        }else {
            return R.error("添加员工失败！");
        }
    }
    @GetMapping("/page")
    public R page(ParamPage page){
        IPage<Employee> page1 = employeeService.page(page);
        if (page1!=null){
            return R.success(page1);
        }
        return R.error("查询失败！");
    }

    @PutMapping
    public R update(@RequestBody Employee employee){
        if (employeeService.update(employee)>0){
            return R.success("更新成功！");
        }
        return R.error("修改失败！");
    }
}
